package com.spring02.demo.utils;

import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JDKDynamicProxy implements InvocationHandler {
    public Object obj;
    //通过构造方法给被代理对象赋值
    public JDKDynamicProxy(Object obj)
    {
        this.obj = obj;
    }

    //产生代理对象
    public Object getProxy(){
        Class<?> aClass = obj.getClass();
        ClassLoader classLoader = aClass.getClassLoader();
        Class<?>[] interfaces = aClass.getInterfaces();
        return Proxy.newProxyInstance(classLoader, interfaces, this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        begin();
        Object invoke = method.invoke(obj, args);
        commit();
        return invoke;
    }

    private void begin() {
        System.out.println("JDK动态代理，监听开始");
    }

    private void commit(){
        System.out.println("JDK动态代理，监听结束");
    }
}
